<?php
/*
 * 系统管理
 * author wangjian
 * time 2013-12-01
 *
 */

if (! defined('BASEPATH')) {
	exit('Access Denied');
}

class Index extends MY_Controller {
	private $username ;//当前登录的用户
	private $ip ; //登录的ip地址
	private $table_ ; //表的前缀
	private $admin ;//创始人
	function Index(){
		parent::__construct();
		$this->load->library('admin_common');//加载admin的公用方法
		date_default_timezone_set('Asia/Shanghai');
		$this->load->model('admin/system/M_system');
		$this->load->model('admin/M_log');
		$this->username = $this->get_login_name(); //得到登录的用户名
		$this->ip = $this->admin_common->get_client_ip();
		$this->table_ = $this->admin_common->table_pre('real_data');
		$this->admin = $this->config->item('web_admin_master');//创始人
	}
	function system_list(){
		
		$data_ = $_REQUEST ;
		$action = 'system_list' ;
		$action_array = array(
			'system_list','ajax_data'
		) ;
		$action = (isset($data_['action']) && in_array($data_['action'], $action_array))?$data_['action']:'system_list';
		
		if($action == 'system_list'){
			$this->load->view('admin/system/views_system_list');
		}elseif($action == 'ajax_data'){
			$this->ajax_get_data();
			die();
		}
	}
	//获取系统列表数据，返回json数据
	private function ajax_get_data(){

		$post_data = $this->input->post(NULL,true) ;
		$where = ' where 1=1';
		
		
		if(isset($post_data['sys_name']) && $post_data['sys_name'] != "" ){
			$sys_name = str_replace("'", "''", strip_tags(htmlspecialchars($post_data['sys_name'])));  //系统名称
			$match_array = array(1=>" AND `sys_user` like '%{$sys_name}%'",2=>" AND `sys_user` = '{$sys_name}'");
			if(isset($post_data['match']) && array_key_exists($post_data['match'], $match_array)){
				$where.=$match_array[$post_data['match']];
			}
			
		}
		if(isset($post_data['id']) && intval($post_data['id']) != "" && intval($post_data['id']) >0){
			$id = intval($post_data['id']);
			$where.=" AND `id` = '{$id}'";
		}
		//$match_array = array(1=>'like');
		
		if(!isset($post_data['page'])){
			$page  =1 ;
		}else{
			$page = intval($post_data['page']);
		}
	
		$sql_count = "SELECT count(*) as tt FROM {$this->table_}common_system_user".$where;
		
		$total = $this->M_system->query_count($sql_count);
		
		$per_page = 10;//每一页显示的数量
		$page_string = $this->page_string($total, $per_page, $page);
		$limit = ($page-1)*$per_page;
		$sql = "SELECT * FROM {$this->table_}common_system_user $where  ORDER BY id DESC LIMIT ".$limit.",".$per_page;
		$res = $this->M_system->querylist($sql);
		if($res){
			foreach($res as $res_k=>$res_v){
				$res[$res_k]['status'] = ($res_v['status'] == "Y")?'正常':'<font color="red">失效</font>';
			}
		}
		$data['result'] = $res ;
		$data['page_string'] = $page_string ;	
		
		echo $this->admin_common->result_to_towf_new($data,'','',null);
	}
	function system_add(){
		//添加系统
		$data_ = $_REQUEST ;
		$action = 'system_list' ;
		$action_array = array(
			'add','add_do'
		) ;
		$action = (isset($data_['action']) && in_array($data_['action'], $action_array))?$data_['action']:'add';
		if($action == 'add'){
			
			$this->load->view('admin/system/views_system_add');
		}elseif($action  == 'add_do'){
			$this->add_do();
		}
		
	}
	private function add_do(){
		$post_data = $this->input->post(NULL,true) ;
		$sys_name = html_escape($this->admin_common->do_addslashes(trim($post_data['sys_name'])));		
		$passwd = html_escape($this->admin_common->do_addslashes(trim($post_data['passwd'])));
		if(iconv_strlen($sys_name,'utf-8') <3 || iconv_strlen($sys_name,'utf-8')>16){
			showmessage('系统用户名称长度必须在3-16之间','admin/system/index/system_add',3,0);
			exit();
		}
		if(iconv_strlen($passwd,'utf-8') <3 || iconv_strlen($passwd,'utf-8')>16){
			showmessage('密码长度必须在3-16之间','admin/system/index/system_add',3,0);
			exit();
		}
		$sql_select = "SELECT id from {$this->table_}common_system_user where sys_user = '{$sys_name}' limit 1 ";
		$row = $this->M_system->querylist($sql_select);
	
		if( isset($row[0]) && is_array($row[0]) && !empty($row[0]) ){
			showmessage("系统系统用户{$sys_name}已经存在",'admin/system/index/system_add',3,0);
			exit();
		}
	
		$data = array(
			'sys_user'=>$sys_name,
			'passwd'=>md5($passwd),
			'addtime'=>date("Y-m-d H:i:s",time()),
			'addperson'=>$this->username,
			'status'=>(isset($post_data['status']) && in_array($post_data['status'],array('Y','N')))?$post_data['status']:'Y'
		);
		
		$array = $this->M_system->insert_one($data,"{$this->table_}common_system_user");
		
		if($array['affect_num'] >=1){
			$this->M_log->insert($array['sql'],'log_system_add',$this->username,$this->ip,1,"添加系统用户{$sys_name}成功"); //插入日志记录
			showmessage("添加系统用户{$sys_name}成功",'admin/system/index/system_list',3,1);
			exit();
		}else{
			$this->M_log->insert($array['sql'],'log_system_add',$this->username,$this->ip,0,"添加系统用户{$sys_name}失败"); //插入日志记录
			showmessage("添加系统用户{$sys_name}失败",'admin/system/index/system_add',3,0);
		}
	
	}
	//编辑
	function system_edit(){
		if($this->admin != $this->username){
			showmessage('对不起只有网站创始人才能执行此操作','admin/system/index/system_list',3,0) ;
			exit();
		}
		$data_ = $_REQUEST ;
		$action = 'system_edit' ;
		$action_array = array(
			'system_edit','system_edit_do'
		) ;
		$action = (isset($data_['action']) && in_array($data_['action'], $action_array))?$data_['action']:'system_edit';
		if($action == 'system_edit'){
		
			$id = (isset($data_['id']) && $data_['id'])?intval($data_['id']):'0';
			$sql_show = "SELECT * FROM `{$this->table_}common_system_user` where id = '{$id}'" ;
			$row = $this->M_system->querylist($sql_show);
			$one = array();
			$one = (isset($row[0])&&!empty($row[0]))?$row[0]:'' ;
			if(empty($one)){
				showmessage("参数错误",'admin/system/index/system_list',3,0);
				exit();
				
			}
			$data = array(
				'one'=>$one
			);
			
			$this->load->view('admin/system/views_system_edit',$data);
		}elseif($action  == 'system_edit_do'){
			$this->system_edit_do();
		}
	}
	//编辑处理
	private function system_edit_do(){
		if($this->admin != $this->username){
			showmessage('对不起只有网站创始人才能执行此操作','admin/system/index/system_list',3,0) ;
			exit();
		}
		$data_ = $_REQUEST ;
		$id = intval($data_['id']);
		$sys_name = html_escape($this->admin_common->do_addslashes(trim($data_['sys_name'])));		
		$passwd = html_escape($this->admin_common->do_addslashes(trim($data_['passwd'])));
		$status = (isset($data_['status']) && in_array($data_['status'],array('Y',"N")))?$data_['status']:'N';
		if(iconv_strlen($sys_name,'utf-8') <3 || iconv_strlen($sys_name,'utf-8')>16){
			showmessage('系统用户名称长度必须在3-16之间','admin/system/index/system_edit?action=system_edit&id='.$id,3,0);
			exit();
		}
		$sql_update = "UPDATE `{$this->table_}common_system_user` set sys_user = '{$sys_name}',status = '{$status}'" ;
		if(!isset($data_['isedit']) ){
			if( iconv_strlen($passwd,'utf-8') <3 || iconv_strlen($passwd,'utf-8')>16){
				showmessage('密码长度必须在3-16之间','admin/system/index/system_edit?action=system_edit&id='.$id,3,0);
				exit();
			}
			$passwd = md5($passwd);
			$sql_update.=" ,passwd = '{$passwd}'";
		}
		$sql_update.=" WHERE id = '{$id}'";
		$num = $this->M_system->update_data($sql_update);
		if($num>=1){
			showmessage('修改成功','admin/system/index/system_list',3,1);
		}else{
			showmessage('修改失败，可能你没有修改任何数据','admin/system/index/system_edit?action=system_edit&id='.$id,3,0);
		}
		
		
	}
	//删除
	function system_del(){
		if($this->admin != $this->username){
			echo $this->admin_common->result_to_towf_new('',0,'对不起只有网站创始人才能执行此操作',null);
			return ;
		}
		$post_data = $_REQUEST;
		$id = ($post_data['id']);
		$in_id = '' ;
		if($id){
			$ids = explode(",", $id);
			for($k = 0 ;$k<count($ids);$k++){
				$in_id.=intval($ids[$k]).",";
			}
		}
		$in_id = rtrim($in_id,",") ;
		if(empty($in_id)){
			echo $this->admin_common->result_to_towf_new('',0,'参数传递出错',null);
			die();
		}
		
		$sql="DELETE FROM `{$this->table_}common_system_user` WHERE id in ($in_id)";
		$num = $this->M_system->del_data($sql);
		$code = 0 ;
		$message = '' ;
		if($num>=1){
			$code = 1 ;
			$message = '删除成功';
			$this->M_log->insert($sql,'log_system_del',$this->username,$this->ip,1,"删除后台用户成功"); //插入日志记录
		}else{
			$code = 0 ;
			$message= '服务器繁忙，或者地址出错' ;
			$this->M_log->insert($sql,'log_system_del',$this->username,$this->ip,0,"删除后台用户失败"); //插入日志记录
		}
		echo $this->admin_common->result_to_towf_new('',$code,$message,null);
		return ;
	}

	/*@function page_string
	 *@分页返回数据
	 *@total 总的数量
	 *@page_num 每一页显示的数量
	 *@page 当前是第几页数据
	 */
	private function page_string($total,$page_num,$page){
		$page_string = '' ;
		$this->load->library('pagination');//加载分页类
		$this->load->library('MY_Pagination');//加载分页类
		$config['total_rows'] = $total;
		$config['use_page_numbers'] =true; // 当前页结束样式
		$config['per_page'] = $page_num; // 每页显示数量，为了能有更好的显示效果，我将该数值设置得较小
		$config['full_tag_open'] = '<div class="pg">'; // 分页开始样式
		$config['full_tag_close'] = '</div>'; // 分页结束样式
		$config['first_link'] = '首页'; // 第一页显示
		$config['last_link'] = '末页'; // 最后一页显示
		$config['next_link'] = '下一页 >'; // 下一页显示
		$config['prev_link'] = '< 上一页'; // 上一页显示
		$config['cur_tag_open'] = ' <a class="current">'; // 当前页开始样式
		$config['cur_tag_close'] = '</a>'; // 当前页结束样式
		$config['uri_segment'] = 6;
		$config['anchor_class']='class="ajax_page" ';
		$this->pagination->cur_page = $page ;
		$this->pagination->initialize($config); // 配置分页
		$page_string =  $this->pagination->create_links(true,'ajax_data');
		return $page_string ;
	}
	
}
